<template>
  <a-modal :width="500" :title="title" v-model="visible" destroyOnClose :maskClosable="false" :confirmLoading="loading" @ok="onSubmit" @cancel="() => (visible = false)">
    <a-spin :delay="100" :spinning="loading">
      <a-form-model ref="sjhtform" :model="form" :rules="rules" :labelCol="lcol" :wrapperCol="wcol" @submit="onSubmit" @submit.native.prevent>
        <a-form-model-item label="上级组织" prop="parentId">
          <span slot="help" style="color:#faad14">不选择任何上级组织默认为一级组织</span>
          <a-tree-select v-model="form.parentId" allowClear :tree-data="treeData" treeDataSimpleMode placeholder="请选择上级组织" />
        </a-form-model-item>
        <a-form-model-item label="组织名称" prop="orgName">
          <a-input v-model="form.orgName" allowClear :maxLength="255" placeholder="请输入组织名称（限255字）" />
        </a-form-model-item>
        <a-form-model-item label="组织描述" prop="orgDesc">
          <a-input v-model="form.orgDesc" allowClear :maxLength="255" placeholder="请输入组织描述（限255字）" />
        </a-form-model-item>
        <a-form-model-item label="状态" prop="status">
          <a-switch v-model="form.status" checkedChildren="启用" unCheckedChildren="停用" />
        </a-form-model-item>
        <input type="submit" v-show="false">
      </a-form-model>
    </a-spin>
  </a-modal>
</template>
<script>
import { pick } from 'lodash'
import { form } from '@/utils/mixins'
import { TreeSelect } from 'ant-design-vue'
import { SaveOrg } from '@/api/manage/org'
export default {
  name: 'SjhtOrgForm', //编辑组织表单
  mixins: [form],
  components: { [TreeSelect.name]: TreeSelect },
  props: {
    parentOrg: {
      type: Array,
      required: true,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      rules: {
        orgName: [{ required: true, whitespace: true, message: '请输入组织名称', trigger: 'blur' }]
      }
    }
  },
  computed: {
    treeData: function () {
      const {
        form: { id }
      } = this
      return this.parentOrg.map(m => ({
        id: m.id,
        pId: m.parentId,
        value: m.id,
        label: m.orgName,
        disabled: m.id == id || (!!id && m.parentId == id)
      }))
    }
  },
  methods: {
    // 打开新建窗口
    create() {
      this.visible = true
      if (this.loading) return
      this.reset()
      this.title = '新建组织'
      this.form = { status: true }
    },
    // 打开修改窗口
    update(data) {
      this.visible = true
      if (this.loading) return
      this.reset()
      this.title = `修改【${data.orgName}】组织`
      const dd = pick(data, ['id', 'parentId', 'orgName', 'orgDesc'])
      Object.assign(dd, { status: Boolean(data.status) })
      this.form = dd
    },
    // 点击确定
    onSubmit(e) {
      e.preventDefault()
      this.$refs.sjhtform.validate(valid => {
        if (!valid) return false
        const { form } = this
        const fd = Object.assign({}, form, { status: form?.status ? 1 : 0 })
        this.submit(SaveOrg, fd)
      })
    }
  }
}
</script>